//
//  HXIflyJobRecordDetailsTableViewController.m
//  KD
//
//  Created by GaoFei on 16/7/8.
//  Copyright © 2016年 Whx. All rights reserved.


//  汇报详情


#import "HXIflyJobRecordDetailsTableViewController.h"

#import "HXIflyJobRecordDetailsHeaderView.h"
#import "HXIflyJobRecordDetailsTableViewCell.h"
#import "HCInputBar.h"
#import "HXAddJobRecViewController.h"
#import "HXReadDayWorkOrCommentModel.h"
#import "NSString+Frame.h"
#import "CNLabel.h"

#import "HXGroupJobTableViewController.h"
#import "HXIflyPersonalDataTableViewController.h"

@interface HXIflyJobRecordDetailsTableViewController ()<UITableViewDataSource,UITableViewDelegate>

/**
 头视图
 */
@property (nonatomic,strong) HXIflyJobRecordDetailsHeaderView * headerView;

/**
 汇报详情Model
 */
@property (nonatomic,strong) HXReadDayWorkOrCommentDetailsModel * headerDetaileModel;
/**
 图片数组
 */
@property (nonatomic,strong) NSArray <HXReadDayWorkOrCommentPiclistModel *>* piclistArr;

/**
 头视图的数据源
 */
@property (nonatomic,strong) NSMutableDictionary * headerDataDic;

/**
 评论人员数组
 */
@property (nonatomic,strong) NSArray <HXReadDayWorkOrCommentReplistModel *>* replistArr;

/**
 UITableView
 */
@property (nonatomic,strong) UITableView * tableView;

//----- UIToolbar
@property (strong, nonatomic) HCInputBar *inputBar;

/**
 textView
 */
@property (nonatomic,strong) UITextView * textView;
@property (nonatomic,copy) NSString * messageId;
@property (nonatomic,copy)NSString *sendUserID;
@property (nonatomic,assign) BOOL isFirstLoad;

@end

@implementation HXIflyJobRecordDetailsTableViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_inputBar.inputView resignFirstResponder];
}

/**
 重写init方法 1.需要MessageID
 */
-(instancetype)initWithMessageID:(NSString *)MessageID withSendUserID:(NSString *)SendUserID{

    if ([super init]) {
        
        self.messageId = MessageID;
        self.sendUserID = SendUserID;
    }
    return self;
}

/**
 创建键盘
 */
-(void)loadCreateKeyboard{

    if (_inputBar == nil) {
        
        _inputBar = [[HCInputBar alloc]initWithStyle:DefaultInputBarStyle];
        _inputBar.keyboard.showAddBtn = NO;
        _inputBar.placeHolder = @"请输入评论...";
        
        //添加输入框键盘模块
        [self.view addSubview:self.inputBar];
        
        //块传值
        __weak typeof(self) weakSelf = self;
        [_inputBar showInputViewContents:^(NSString *contents) {
            
            [weakSelf updateMessage:contents];
        }];
    }
}

/**
 发送评论
 */
- (void)updateMessage:(NSString *)message{

    [SVProgressHUD showWithStatus:@"正在发表评论..."];
    [NetworkAPI AddRepDayWorkWithMessageID:self.messageId withContent:message Success:^(HXBaseModel *result) {
        
        if ([result.code isEqualToString:@"200"]) {
            
//            [SVProgressHUD showSuccessWithStatus:@"发表成功"];
            //
            [self loadCreateData];
            
            [_inputBar.inputView resignFirstResponder];
        }
        
    } failure:^(NSError *err) {
        
        [SVProgressHUD showErrorWithStatus:@"网络错误!"];
    }];
    
    NSLog(@"--------- fasongde xiaoxishi is %@",message);
}

/**创建头视图 和 UITableView*/
-(void)loadCreateHeaderViewAndTableView{
    
//    self.navigationController.navigationBar.translucent = NO;
    
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, HXSCREEN_WIDTH, HXSCREEN_HEIGHT-49-64) style:UITableViewStylePlain];
        
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.alwaysBounceVertical = YES;
        
        [self.view addSubview:_tableView];
    }
    if (_headerView == nil) {
        
        //-----//计算图片的高度//----------//
        CGFloat imgH = 0;
        if (self.piclistArr.count > 0) {
            
            NSMutableArray *urls = [NSMutableArray array];
            
            for (HXReadDayWorkOrCommentPiclistModel *picModel in self.piclistArr) {
                
                [urls addObject:picModel.Pic_Path];
            }
            
            WBImageView *_imgV = [[WBImageView alloc]initWithFrame:CGRectMake(25, 0, 300, 0)];
            
            //图片赋值数据
            _imgV.data = urls;
            
            imgH = _imgV.height;
        }
        
        CNLabel * cnlabel = [[CNLabel alloc]initWithFrame:CGRectMake(0, 0, HXSCREEN_WIDTH-16, 0)];
        //设置文本
        cnlabel.text = [NSString stringWithFormat:@"%@",self.headerDetaileModel.Content];
        
        _headerView = [[[NSBundle mainBundle] loadNibNamed:@"HXIflyJobRecordDetailsHeaderView" owner:nil options:nil] objectAtIndex:0];
        
        _headerView.frame = CGRectMake(0, 64, _headerView.width, cnlabel.height+90-13+imgH);
        
        _headerView.dataDic = self.headerDataDic;
        
        [self.tableView setTableHeaderView:_headerView];
        
        _isFirstLoad = YES;
    }
    //[self.view insertSubview:self.headerView aboveSubview:self.tableView];
    [self.view bringSubviewToFront:self.inputBar];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //加载数据
    [self loadCreateData];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

-(void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

/**
 加载数据
 */
-(void)loadCreateData{
    
    //初始化数据源字典
    _headerDataDic = [NSMutableDictionary dictionary];
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    [NetworkAPI getReadDayWorkDetailesOrCommentWithMessageID:self.messageId
                                                     Success:^(HXReadDayWorkOrCommentModel *result) {
        
                                                         if ([result.code isEqualToString:@"200"]) {
            
                                                             self.tableView = nil;
                                                             self.headerView = nil;
//                                                             self.inputBar = nil;
                                                             
                                                             [SVProgressHUD showSuccessWithStatus:@"加载成功!"];
                                                             self.headerDetaileModel = result.details;
                                                             self.replistArr = result.replist;
                                                             self.piclistArr = result.piclist;
                                                        [self.headerDataDic setObject:self.headerDetaileModel forKey:@"detail"];
                                                             [self.headerDataDic setObject:self.piclistArr forKey:@"piclist"];
                                                             _headerView.dataDic = self.headerDataDic;
                                                             //创建头视图及TableView
                                                             [self loadCreateHeaderViewAndTableView];
                                                             //创建键盘
                                                             [self loadCreateKeyboard];
                                                             
//                                                             [self.tableView reloadData];
                                                             
//                                                             if (![[UserDefaultHandler getUserDetault:kID] isEqualToString:self.headerDetaileModel.AuthorID]) {
//                                                                 self.navigationItem.rightBarButtonItem.enabled = NO;
//                                                             }
                                                         }
                                                     } failure:^(NSError *err) {
                                                         [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                                     }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _isFirstLoad = NO;
    self.navigationItem.title = @"汇报详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([self.sendUserID isEqualToString:[UserDefaultHandler getUserDetault:kID]]) {
        UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"编辑"
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:self
                                                                        action:@selector(rightBarBtnClick)];
        rightBarBtn.tintColor = [UIColor redColor];
        self.navigationItem.rightBarButtonItem = rightBarBtn;

    }
    
    UIButton *backButton=[[UIButton alloc]init];
    // 设置返回图片
    [backButton setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
    backButton.contentMode = UIViewContentModeLeft;
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //[button sizeToFit];//让按钮大小跟随内容
    //让按钮的内容往左边偏移10
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame=CGRectMake(0, 0,37,90);
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:backButton];

//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backButton)];
}

/**
 返回到上一级
 */
-(void)backButton{

    if (_jiemianID == 1) {
        
        [self.groupSupVC loadCreateData];
    }else if (_jiemianID == 2){
    
        [self.personSupVC loadCreateDataMethod];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 修改日报
 */
-(void)rightBarBtnClick {
    
    HXAddJobRecViewController * editJobRecVc = [[HXAddJobRecViewController alloc] initWithMessageID:self.messageId];
    
    editJobRecVc.type = ChangeJobRecordType;
    editJobRecVc.changeSuperVC = self;
    editJobRecVc.dayWorkCon = self.headerDetaileModel.Content;
    editJobRecVc.datWorkTime = self.headerDetaileModel.SendDate;
    editJobRecVc.getPhotoArr = self.piclistArr;
    
    [self.navigationController pushViewController:editJobRecVc animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.replistArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HXIflyJobRecordDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXIflyJobRecordDetailsTableViewCell"];
    
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HXIflyJobRecordDetailsTableViewCell" owner:nil options:nil] objectAtIndex:0];
    }
    
    HXReadDayWorkOrCommentReplistModel * model = self.replistArr[indexPath.row];
    
    cell.replistModel = model;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat cellHeight = 70.f-13.f;
    
    HXReadDayWorkOrCommentReplistModel * model = self.replistArr[indexPath.row];

    if (model.MC_Content.length > 0) {
        
        cellHeight = cellHeight + [model.MC_Content heightWithFont:[UIFont systemFontOfSize:15] withinWidth:HXSCREEN_WIDTH-3*8];
    }
    
    return cellHeight;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView * cellBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HXSCREEN_WIDTH, 46)];
    cellBgView.backgroundColor = HXCustomColor(239, 239, 244, 1);
    
    
    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, HXSCREEN_WIDTH, 36)];
    bgView.backgroundColor = [UIColor whiteColor];
    [cellBgView addSubview:bgView];

    
    UILabel * replistLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, HXSCREEN_WIDTH-8*2, 36)];
    replistLabel.text = [NSString stringWithFormat:@"评论  %ld",self.replistArr.count];
    [bgView addSubview:replistLabel];
    
    return cellBgView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 46.f;
}


@end
